<!-- 工序管理 -->
<template>
  <div class="process-management">
    <div class="title-section">
      <h2>工序管理</h2>
      <el-button class="btn-primary" type="primary" @click="openCreateDialog">新建</el-button>
    </div>

    <!-- 筛选区域 -->
    <div class="controls-section">
      <el-form :inline="true" :model="query" class="filters">
        <el-form-item label="工序编号">
          <el-input v-model="query.processCode" placeholder="请输入工序编号" clearable />
        </el-form-item>
        <el-form-item label="工序名称">
          <el-input v-model="query.processName" placeholder="请输入工序名称" clearable />
        </el-form-item>
        <el-form-item label="工序类型">
          <el-select v-model="query.processType" placeholder="全部" clearable style="width: 150px;">
            <el-option :value="0" label="自制" />
            <el-option :value="1" label="委外" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="query.status" placeholder="全部" clearable style="width: 150px;">
            <el-option :value="0" label="启用" />
            <el-option :value="1" label="禁用" />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="actions">
        <el-button class="btn-primary" type="primary" @click="handleSearch">搜索</el-button>
        <el-button class="btn-secondary" @click="handleReset">重置</el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-table :data="tableData" style="width: 100%" border v-loading="loading">
        <el-table-column type="selection" width="48" />
        <el-table-column label="工序名称" min-width="180">
          <template #default="{ row }">
            <span class="link-style" @click="viewDetail(row)">{{ row.processName }}</span>
            <div class="sub">{{ row.processCode }}</div>
          </template>
        </el-table-column>
        <el-table-column label="工序类型" width="100">
          <template #default="{ row }">
            <span>{{ formatProcessType(row.processType) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="工序单位" width="120">
          <template #default="{ row }">
            <span>{{ row.unitName || row.unitId || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="工序执行人" width="140">
          <template #default="{ row }">
            <span>{{ row.executorName || row.uId || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="工序单价" width="120">
          <template #default="{ row }">{{ formatPrice(row.unitPrice) }}</template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="160" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 0 ? 'success' : 'info'">{{ row.status === 0 ? '启用' : '禁用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="160">
          <template #default="{ row }">
            <el-button class="btn-link" link type="primary" size="small" @click="openEditDialog(row)">编辑</el-button>
            <el-popconfirm :title="`确认删除【${row.processName}】吗？`" @confirm="handleDelete(row)">
              <template #reference>
                <el-button class="btn-link btn-danger" link type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 底部区域 -->
    <div class="footer-section">
      <div class="footer-left">
        <el-button class="btn-secondary" @click="handleExport">导出</el-button>
      </div>
      <div class="pagination">
        <el-pagination
            background
            layout="prev, pager, next, sizes, total"
            :total="total"
            :page-sizes="[10, 20, 50]"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="onCurrentChange"
            @size-change="onSizeChange"
        />
      </div>
    </div>

    <!-- 新建/编辑 弹窗 -->
    <el-dialog :title="isEditing ? '编辑工序' : '新建工序'" v-model="dialogVisible" width="560px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="96px">
        <el-form-item label="工序名称" prop="processName">
          <el-input v-model="form.processName" placeholder="请输入工序名称" />
        </el-form-item>
        <el-form-item label="工序类型" prop="processType">
          <el-select v-model="form.processType" placeholder="请选择" style="width: 220px;">
            <el-option :value="0" label="自制" />
            <el-option :value="1" label="委外" />
          </el-select>
        </el-form-item>
        <el-form-item label="工序单位" prop="unitId">
          <el-input v-model="form.unitId" placeholder="请输入单位ID" />
        </el-form-item>
        <el-form-item label="执行人" prop="uId">
          <el-input v-model="form.uId" placeholder="请输入执行人ID" />
        </el-form-item>
        <el-form-item label="单价" prop="unitPrice">
          <el-input v-model.number="form.unitPrice" placeholder="请输入单价" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="0">启用</el-radio>
            <el-radio :value="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button class="btn-secondary" @click="dialogVisible = false">取 消</el-button>
          <el-button class="btn-primary" type="primary" :loading="submitLoading" @click="handleSubmit">保 存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 工序详情 弹窗 -->
    <el-dialog title="工序详情" v-model="detailDialogVisible" width="600px">
      <div class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工序编号" :span="2">
            <span class="detail-value">{{ detailData.processCode || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="工序名称" :span="2">
            <span class="detail-value">{{ detailData.processName || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="工序类型">
            <el-tag :type="detailData.processType === 0 ? 'success' : 'warning'">
              {{ formatProcessType(detailData.processType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="detailData.status === 0 ? 'success' : 'info'">
              {{ detailData.status === 0 ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="工序单位">
            <span class="detail-value">{{ detailData.unitName || detailData.unitId || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="工序执行人">
            <span class="detail-value">{{ detailData.executorName || detailData.uId || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="工序单价" :span="2">
            <span class="detail-value price">{{ formatPrice(detailData.unitPrice) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            <span class="detail-value">{{ detailData.remark || '-' }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button class="btn-secondary" @click="detailDialogVisible = false">关 闭</el-button>
          <el-button class="btn-primary" type="primary" @click="openEditFromDetail">编 辑</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { processApi } from '@/api/process'
import { ElMessage } from 'element-plus'
import { reactive, ref, onMounted } from 'vue'

export default {
  name: 'ProcessManagement',
  setup() {
    const loading = ref(false)
    const tableData = ref([])

    const query = reactive({
      processCode: '',
      processName: '',
      processType: undefined, // 0 自制, 1 委外
      status: undefined, // 0 启用, 1 禁用
    })

    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)

    const dialogVisible = ref(false)
    const isEditing = ref(false)
    const submitLoading = ref(false)
    const formRef = ref(null)
    
    // 详情弹窗相关
    const detailDialogVisible = ref(false)
    const detailData = ref({})

    const form = reactive({
      processId: undefined,
      processName: '',
      processType: undefined,
      unitId: undefined,
      uId: undefined,
      unitPrice: undefined,
      remark: '',
      status: 0,
    })

    const rules = {
      processName: [{ required: true, message: '请输入工序名称', trigger: 'blur' }],
      processType: [{ required: true, message: '请选择工序类型', trigger: 'change' }],
      unitId: [{ required: true, message: '请输入工序单位ID', trigger: 'blur' }],
      unitPrice: [{ required: true, message: '请输入单价', trigger: 'blur' }],
      status: [{ required: true, message: '请选择状态', trigger: 'change' }],
    }

    function formatProcessType(value) {
      if (value === 0) return '自制'
      if (value === 1) return '委外'
      return '-'
    }

    function formatPrice(val) {
      if (val === null || val === undefined || val === '') return '-'
      const num = Number(val)
      return isNaN(num) ? '-' : num.toFixed(2)
    }

    // 兼容后端返回 Map<String,Object> 场景（下划线字段名）
    function normalizeRow(r = {}) {
      return {
        processId: r.processId ?? r.process_id ?? r.id,
        processCode: r.processCode ?? r.process_code,
        processName: r.processName ?? r.process_name,
        processType: r.processType ?? r.process_type,
        unitId: r.unitId ?? r.unit_id ?? r.unit,
        unitName: r.unitName ?? r.unit_name ?? r.unitNameZh ?? r.unit_text,
        uId: r.uId ?? r.u_id ?? r.executorId ?? r.executor_id,
        executorName: r.executorName ?? r.executor_name ?? r.u_name ?? r.userName ?? r.username,
        unitPrice: r.unitPrice ?? r.unit_price,
        remark: r.remark,
        status: r.status,
      }
    }

    async function fetchPage() {
      loading.value = true
      try {
        const params = {
          current: currentPage.value,
          size: pageSize.value,
          processCode: query.processCode || undefined,
          processName: query.processName || undefined,
          processType: query.processType,
          status: query.status,
        }
        const { data } = await processApi.page(params)
        // 兼容不同后端分页结构：MyBatis-Plus IPage 或自定义 Result
        const payload = data?.data || data
        // 尝试识别字段
        const records = payload?.records || payload?.items || payload?.list || []
        const totalCount = payload?.total || payload?.totalCount || 0
        tableData.value = records.map(normalizeRow)
        total.value = totalCount
      } finally {
        loading.value = false
      }
    }

    function handleSearch() {
      currentPage.value = 1
      fetchPage()
    }

    function handleReset() {
      query.processCode = ''
      query.processName = ''
      query.processType = undefined
      query.status = undefined
      handleSearch()
    }

    function onCurrentChange(page) {
      currentPage.value = page
      fetchPage()
    }

    function onSizeChange(size) {
      pageSize.value = size
      currentPage.value = 1
      fetchPage()
    }

    function openCreateDialog() {
      isEditing.value = false
      Object.assign(form, {
        processId: undefined,
        processName: '',
        processType: undefined,
        unitId: undefined,
        uId: undefined,
        unitPrice: undefined,
        remark: '',
        status: 0,
      })
      dialogVisible.value = true
    }

    function openEditDialog(row) {
      isEditing.value = true
      Object.assign(form, {
        processId: row.processId,
        processName: row.processName,
        processType: row.processType,
        unitId: row.unitId,
        uId: row.uId,
        unitPrice: row.unitPrice,
        remark: row.remark,
        status: row.status,
      })
      dialogVisible.value = true
    }

    async function viewDetail(row) {
      // 根据ID查询工序详细信息并显示详情弹窗
      if (!row?.processId) return
      try {
        const { data } = await processApi.getById(row.processId)
        const payload = data?.data || data
        if (payload) {
          const processDetail = normalizeRow(payload)
          // 设置详情数据并显示详情弹窗
          detailData.value = processDetail
          detailDialogVisible.value = true
        }
      } catch (e) {
        ElMessage.error('获取工序详情失败')
      }
    }

    async function handleSubmit() {
      if (!formRef.value) return
      await formRef.value.validate(async (valid) => {
        if (!valid) return
        submitLoading.value = true
        try {
          if (isEditing.value) {
            await processApi.update(form)
            ElMessage.success('工序信息修改成功')
          } else {
            await processApi.add(form)
            ElMessage.success('工序信息添加成功')
          }
          dialogVisible.value = false
          fetchPage()
        } finally {
          submitLoading.value = false
        }
      })
    }

    async function handleDelete(row) {
      if (!row?.processId) return
      try {
        await processApi.delete(row.processId)
        ElMessage.success('删除成功')
        // 如果本页只剩 1 条，删除后回到上一页
        if (tableData.value.length === 1 && currentPage.value > 1) {
          currentPage.value -= 1
        }
        fetchPage()
      } catch (e) {
        // 已有全局错误提示
      }
    }

    function openEditFromDetail() {
      // 从详情弹窗直接进入编辑模式
      isEditing.value = true
      Object.assign(form, {
        processId: detailData.value.processId,
        processName: detailData.value.processName,
        processType: detailData.value.processType,
        unitId: detailData.value.unitId,
        uId: detailData.value.uId,
        unitPrice: detailData.value.unitPrice,
        remark: detailData.value.remark,
        status: detailData.value.status,
      })
      detailDialogVisible.value = false
      dialogVisible.value = true
    }

    function handleExport() {
      // 简单导出当前筛选条件下的表格为 CSV（前端导出演示）
      const rows = tableData.value
      if (!rows?.length) {
        ElMessage.info('暂无可导出数据')
        return
      }
      const headers = ['工序编号', '工序名称', '工序类型', '单位', '执行人', '单价', '状态', '备注']
      const csvRows = [headers.join(',')]
      rows.forEach((r) => {
        csvRows.push([
          r.processCode || '',
          r.processName || '',
          formatProcessType(r.processType),
          (r.unitName || r.unitId || ''),
          (r.executorName || r.uId || ''),
          formatPrice(r.unitPrice),
          r.status === 0 ? '启用' : '禁用',
          (r.remark || '').replaceAll(',', '，'),
        ].join(','))
      })
      const blob = new Blob(['\ufeff' + csvRows.join('\n')], { type: 'text/csv;charset=utf-8;' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `工序列表_${Date.now()}.csv`
      a.click()
      URL.revokeObjectURL(url)
    }

    onMounted(fetchPage)

    return {
      // state
      loading,
      tableData,
      query,
      currentPage,
      pageSize,
      total,
      dialogVisible,
      isEditing,
      submitLoading,
      form,
      formRef,
      rules,
      detailDialogVisible,
      detailData,
      // methods
      fetchPage,
      handleSearch,
      handleReset,
      onCurrentChange,
      onSizeChange,
      openCreateDialog,
      openEditDialog,
      openEditFromDetail,
      handleSubmit,
      handleDelete,
      viewDetail,
      handleExport,
      // formatters
      formatProcessType,
      formatPrice,
    }
  },
}
</script>

<style scoped>
.process-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}
.title-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.title-section h2 {
  font-size: 20px;
  font-weight: bold;
}
.controls-section {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 16px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  align-items: center;
}
.filters {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
}
.actions {
  display: flex;
  gap: 10px;
}
.table-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
}
.link-style { color: #409eff; cursor: pointer; }
.sub { color: #666; font-size: 12px; }
.footer-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 8px;
}
.footer-left { display: flex; align-items: center; gap: 8px; }
.pagination { display: flex; align-items: center; gap: 8px; }

/* 引入与 BOMManagement 一致的按钮样式 */
.btn-primary {
  background-color: #409eff;
  color: white;
  border: none;
}
.btn-primary:hover { background-color: #66b1ff; }
.btn-primary:disabled { background-color: #a0cfff; cursor: not-allowed; }

.btn-secondary {
  background-color: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
}
.btn-secondary:hover {
  color: #409eff;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
}

.btn-link {
  background: none;
  border: none;
  color: #409eff;
  cursor: pointer;
  padding: 0;
}
.btn-link.btn-danger { color: #f56c6c; }

/* 详情弹窗样式 */
.detail-content {
  padding: 10px 0;
}
.detail-value {
  color: #303133;
  font-weight: 500;
}
.detail-value.price {
  color: #e6a23c;
  font-weight: 600;
  font-size: 16px;
}

/* 优化descriptions样式 */
:deep(.el-descriptions__body .el-descriptions__table .el-descriptions__cell) {
  padding: 12px 16px;
}
:deep(.el-descriptions__label) {
  font-weight: 600;
  color: #606266;
  background-color: #fafafa;
}
:deep(.el-descriptions__content) {
  background-color: #fff;
}
</style>


